﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Caliburn.Micro;
using Wulong.Phone.Dianping.Constants;
using Wulong.Phone.Dianping.Messages;
using Wulong.Phone.Dianping.Models;
using Wulong.Phone.Dianping.Services;
using Wulong.Phone.Dianping.Utils;

namespace Wulong.Phone.Dianping.ViewModels
{
    public class YourCityViewModel : Screen
    {
        private INavigationService _navigation;
        IEventAggregator _events; 
        public YourCityViewModel(
            INavigationService navigation,
            IEventAggregator events)
        {
            _cities = new ObservableCollection<City>();
            _navigation = navigation;
            _events = events;
        }

        protected override void OnViewReady(object view)
        {
            base.OnViewReady(view);

            if(_cities.Count == 0)
            {
                RenderCityPicker();
            }
        }

        private void RenderCityPicker()
        {
            string myCityCode;
            bool hasValue = AppSettings.TryGetSetting(
                CommonConstants.MyCityStorageKey,
                out myCityCode);
            DianpingService
                .ObservableCity()
                .Subscribe(item =>
                               {
                                   _cities.Add(item);
                                   if (hasValue &&
                                       item.Code.Equals(myCityCode))
                                       SelectedCity = item;
                               },
                               ()=>
                                   {
                                       if (SelectedCity==null)
                                           SelectedCity = _cities[0];
                                   });
        }

        private ObservableCollection<City> _cities;
        public IEnumerable<City> Cities
        {
            get { return _cities; }
        }

        private City _selectedCity;
        public City SelectedCity
        {
            get { return _selectedCity; }
            set
            {
                _selectedCity = value;
                NotifyOfPropertyChange(()=>SelectedCity);
            }
        }

        public void SaveMyCity()
        {
            if (SelectedCity == null) return;
            AppSettings.StoreSetting(
                CommonConstants.MyCityStorageKey, SelectedCity.Code);
            _events.Publish(new RefreshMainView());
            _navigation.UriFor<MainViewModel>()
                .WithParam(x => x.CityCode, SelectedCity.Code)
                .WithParam(x => x.CityPinyin, SelectedCity.Pinyin)
                .Navigate();
        }
    }
}
